package com.water.camera.activity.camera

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager.PERMISSION_GRANTED
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Color
import android.graphics.ImageFormat
import android.graphics.PointF
import android.graphics.Rect
import android.graphics.YuvImage
import android.media.MediaMetadataRetriever
import android.os.Bundle
import android.os.CountDownTimer
import android.text.TextUtils
import android.util.AttributeSet
import android.util.Log
import android.view.View
import android.view.ViewGroup
import android.view.ViewGroup.LayoutParams.MATCH_PARENT
import android.view.ViewGroup.LayoutParams.WRAP_CONTENT
import android.widget.FrameLayout
import android.widget.RelativeLayout
import com.otaliastudios.cameraview.CameraException
import com.otaliastudios.cameraview.CameraListener
import com.otaliastudios.cameraview.CameraLogger
import com.otaliastudios.cameraview.CameraOptions
import com.otaliastudios.cameraview.CameraView
import com.otaliastudios.cameraview.PictureResult
import com.otaliastudios.cameraview.VideoResult
import com.otaliastudios.cameraview.controls.Facing
import com.otaliastudios.cameraview.controls.Flash
import com.otaliastudios.cameraview.controls.Mode
import com.otaliastudios.cameraview.controls.Preview
import com.otaliastudios.cameraview.frame.Frame
import com.otaliastudios.cameraview.frame.FrameProcessor
import com.plata.base.aclr.common.SilentTask
import com.plata.base.aclr.common.TaskEngine
import com.plata.base.aclr.utils.SPHelper
import com.qmuiteam.qmui.kotlin.onClick
import com.water.camera.App
import com.water.camera.BuildConfig
import com.water.camera.R
import com.water.camera.activity.BaseActivity
import com.water.camera.activity.PreviewPhotoAct
import com.water.camera.databinding.ActivityCameraBinding
import com.water.camera.fragment.MarkDlg
import com.water.camera.it.WaterMarkViewChangeListener
import com.water.camera.mark.BaseMark
import com.water.camera.mark.Mark1
import com.water.camera.util.Read
import com.water.camera.util.SaveUtils
import com.water.camera.util.ToastUtil
import com.water.camera.util.Utils
import java.io.ByteArrayOutputStream
import java.io.File


class CameraActivity : BaseActivity(), View.OnClickListener, OptionView.Callback,
    WaterMarkViewChangeListener {

    companion object {
        private val LOG = CameraLogger.create("DemoApp")
        private const val USE_FRAME_PROCESSOR = false
        private const val DECODE_BITMAP = false
    }

    private val camera: CameraView by lazy { findViewById(R.id.camera) }
    private var captureTime: Long = 0

    private var waterMark: BaseMark? = null
    private var scale = -1f
    private lateinit var binding: ActivityCameraBinding
    private val sizeTabs = ArrayList<SizeTab>()
    private var zoomIndex = 2

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityCameraBinding.inflate(layoutInflater)
        setContentView(binding.getRoot())

        sizeTabs.add(
            SizeTab(
                binding.size.icCameraRatio34,
                binding.size.icCameraRatio34Select,
                this
            )
        )
        sizeTabs.add(
            SizeTab(
                binding.size.icCameraRatio916,
                binding.size.icCameraRatio916Select,
                this
            )
        )
        sizeTabs.add(
            SizeTab(
                binding.size.icCameraRatio11,
                binding.size.icCameraRatio11Select,
                this
            )
        )
        sizeTabs.add(
            SizeTab(
                binding.size.icCameraRatioFull,
                binding.size.icCameraRatioFullSelect,
                this
            )
        )

        CameraLogger.setLogLevel(CameraLogger.LEVEL_VERBOSE)
        camera.setLifecycleOwner(this)
        camera.addCameraListener(Listener())
        if (USE_FRAME_PROCESSOR) {
            camera.addFrameProcessor(object : FrameProcessor {
                private var lastTime = System.currentTimeMillis()
                override fun process(frame: Frame) {
                    val newTime = frame.time
                    val delay = newTime - lastTime
                    lastTime = newTime
                    LOG.v("Frame delayMillis:", delay, "FPS:", 1000 / delay)
                    if (DECODE_BITMAP) {
                        if (frame.format == ImageFormat.NV21
                            && frame.dataClass == ByteArray::class.java
                        ) {
                            val data = frame.getData<ByteArray>()
                            val yuvImage = YuvImage(
                                data,
                                frame.format,
                                frame.size.width,
                                frame.size.height,
                                null
                            )
                            val jpegStream = ByteArrayOutputStream()
                            yuvImage.compressToJpeg(
                                Rect(
                                    0, 0,
                                    frame.size.width,
                                    frame.size.height
                                ), 100, jpegStream
                            )
                            val jpegByteArray = jpegStream.toByteArray()
                            val bitmap = BitmapFactory.decodeByteArray(
                                jpegByteArray,
                                0, jpegByteArray.size
                            )
                            bitmap.toString()
                        }
                    }
                }
            })
        }
        binding.frame.ratio = 1.33
        binding.ivAlbum.setNeedRadiu(true)
        binding.ivAlbum.setRadiusInDip(2)
        findViewById<View>(R.id.gallery).setOnClickListener(this)
        findViewById<View>(R.id.mark).setOnClickListener(this)
        findViewById<View>(R.id.capturePictureSnapshot).setOnClickListener(this)
        binding.ivLight.setOnClickListener(this)
        binding.ivCameraSwitch.setOnClickListener(this)
        binding.timing.setOnClickListener(this)
        binding.tvPuzzle.setOnClickListener(this)
        binding.backIv.onClick { finish() }
        binding.zoom.view1.onClick { zoom(0) }
        binding.zoom.view2.onClick { zoom(1) }
        binding.zoom.view3.onClick { zoom(2) }

        binding.videoTv.onClick { changeMode(Mode.VIDEO) }
        binding.takePhotosTv.onClick { changeMode(Mode.PICTURE) }

        var name: String?
        if (intent.hasExtra("name")) {
            name = intent.getStringExtra("name")
        } else {
            name = Mark1::class.java.name
        }
        try {
            val view = Class.forName(name).getDeclaredConstructor(
                Context::class.java,
                AttributeSet::class.java
            )
                .newInstance(this, null) as BaseMark
            onWaterMarkViewChange(view)
        } catch (e: Throwable) {
            e.printStackTrace()
        }
    }

    private fun changeMode(mode: Mode) {
        if (camera.isTakingPicture || camera.isTakingVideo || countDown || camera.mode == mode) {
            return
        }
        camera.mode = mode
        if (mode == Mode.PICTURE) {
            binding.tvWater.text = "水印"
            binding.takePhotosTv.setBackgroundResource(R.drawable.shadow15_gray)
            binding.videoTv.background = null
            binding.tvPuzzle.isEnabled = true
            binding.ivTakeCenter.setImageResource(R.drawable.bg_camera_take_blue_center)
            changeSize(0)
        } else {
            binding.videoTv.setBackgroundResource(R.drawable.shadow15_gray)
            binding.ivTakeCenter.setImageResource(R.drawable.bg_camera_take_video_normal)
            binding.takePhotosTv.background = null
            binding.tvPuzzle.isEnabled = false
            binding.size.root.visibility = View.GONE
            changeSize(1)
        }
    }

    private fun zoom(i: Int) {
        if (zoomIndex == i) {
            return
        }
        when (i) {
            0 -> {
                binding.zoom.view1.visibility = View.GONE
                binding.zoom.value1.visibility = View.VISIBLE
                camera.zoom = 1f
            }

            1 -> {
                binding.zoom.view2.visibility = View.GONE
                binding.zoom.value2.visibility = View.VISIBLE
                camera.zoom = 0.2f
                binding.zoom.value2.text = "2x"
            }

            2 -> {
                binding.zoom.view3.visibility = View.GONE
                binding.zoom.value3.visibility = View.VISIBLE
                camera.zoom = 0f
            }
        }
        when (zoomIndex) {
            0 -> {
                binding.zoom.view1.visibility = View.VISIBLE
                binding.zoom.value1.visibility = View.GONE
            }

            1 -> {
                binding.zoom.view2.visibility = View.VISIBLE
                binding.zoom.value2.visibility = View.GONE
            }

            2 -> {
                binding.zoom.view3.visibility = View.VISIBLE
                binding.zoom.value3.visibility = View.GONE
            }
        }
        zoomIndex = i
    }

    override fun onWaterMarkViewChange(mark: BaseMark?) {
//        if (markDlg != null) {
//            markDlg!!.dismiss()
//        }
        binding.rotateView.removeAllViews()
        if (mark != null) {
            var params = binding.rotateView.layoutParams as FrameLayout.LayoutParams
            if (mark.isFullScreen) {
                params.width = MATCH_PARENT
                params.height = MATCH_PARENT
                params.leftMargin = 0
                params.rightMargin = 0
                params.topMargin = 0
                params.bottomMargin = 0
                binding.rotateView.translationX = 0f
                binding.rotateView.translationY = 0f
                binding.rotateView.isEnabled = false
                var tmp = ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT)
                binding.rotateView.addView(mark, tmp)
            } else if (mark.isFullWidth) {
                params.width = MATCH_PARENT
                params.height = WRAP_CONTENT
                params.rightMargin = 0
                params.leftMargin = 0
                binding.rotateView.translationX = 0f
                params.bottomMargin = params.rightMargin
                var tmp = ViewGroup.LayoutParams(MATCH_PARENT, WRAP_CONTENT)
                binding.rotateView.addView(mark, tmp)
            } else {
                if (params.width == MATCH_PARENT) {
                    params.width = WRAP_CONTENT
                    params.height = WRAP_CONTENT
                    params.rightMargin = Utils.dp2Px(this, 15f)
                    params.bottomMargin = params.rightMargin
                }
                binding.rotateView.isEnabled = true
                binding.rotateView.addView(mark)
            }
        }
        waterMark = mark
        var key = mark!!::class.java.simpleName + "_scale"
        var scale = SPHelper.getInstance(this).getFloat(key, 1.0f)
        binding.rotateView.scaleX = scale
        binding.rotateView.scaleY = scale
        camera.setWatermark(binding.rotateView)
    }

    override fun needScale(): Boolean {
        return false
    }

    private fun message(content: String, important: Boolean) {
        if (!BuildConfig.DEBUG) {
            return
        }
        Log.e("tagg", content);
//        if (important) {
//            LOG.w(content)
//            Toast.makeText(this, content, Toast.LENGTH_LONG).show()
//        } else {
//            LOG.i(content)
//            Toast.makeText(this, content, Toast.LENGTH_SHORT).show()
//        }
    }

    private inner class Listener : CameraListener() {
        override fun onCameraOpened(options: CameraOptions) {
        }

        override fun onOrientationChanged(orientation: Int) {
            binding.rotateView.angle = orientation
        }

        override fun onCameraError(exception: CameraException) {
            super.onCameraError(exception)
            message("Got CameraException #" + exception.reason, true)
        }

        override fun onPictureTaken(result: PictureResult) {
            super.onPictureTaken(result)
            if (camera.isTakingVideo) {
                message("Captured while taking video. Size=" + result.size, false)
                return
            }

            // This can happen if picture was taken with a gesture.
            val callbackTime = System.currentTimeMillis()
            if (captureTime == 0L) captureTime = callbackTime - 300
            LOG.w("onPictureTaken called! Launching activity. Delay:", callbackTime - captureTime)
            try {
                result.toBitmap(10000, 10000) { bitmap ->
                    var bo = SaveUtils.saveBitmapToAlbum(
                        App.getApp(),
                        bitmap
                    )
                    if (bo) {
                        binding.ivAlbum.setImageBitmap(bitmap)
                        ToastUtil.showShortToast(App.getApp(), "导出成功");
                    } else {
                        ToastUtil.showShortToast(App.getApp(), "导出失败");
                    }
                }
            } catch (e: Throwable) {
                ToastUtil.showShortToast(App.getApp(), "导出失败");
            }
            captureTime = 0
//            LOG.w("onPictureTaken called! Launched activity.")
        }

        override fun onVideoTaken(result: VideoResult) {
            super.onVideoTaken(result)
            LOG.w("onVideoTaken called! Launching activity.")
            if (saveVideo) {
                saveVideo()
            }
//            VideoPreviewActivity.videoResult = result
//            val intent = Intent(this@CameraActivity, VideoPreviewActivity::class.java)
//            startActivity(intent)
//            LOG.w("onVideoTaken called! Launched activity.")
        }

        override fun onVideoRecordingStart() {
            super.onVideoRecordingStart()
            LOG.w("onVideoRecordingStart!")
        }

        override fun onVideoRecordingEnd() {
            super.onVideoRecordingEnd()
            message("Video taken. Processing...", false)
            LOG.w("onVideoRecordingEnd!")
        }

        override fun onExposureCorrectionChanged(
            newValue: Float,
            bounds: FloatArray,
            fingers: Array<PointF>?
        ) {
            super.onExposureCorrectionChanged(newValue, bounds, fingers)
            message("Exposure correction:$newValue", false)
        }

        override fun onZoomChanged(newValue: Float, bounds: FloatArray, fingers: Array<PointF>?) {
            super.onZoomChanged(newValue, bounds, fingers)
            if (newValue >= 0.95f) {
                zoom(0)
            } else if (newValue < 0.1f) {
                zoom(2)
            } else {
                zoom(1)
                binding.zoom.value2.text = String.format("%.1f", newValue * 10) + "x"
            }
        }
    }

    override fun onClick(view: View) {
        when (view.id) {
            R.id.capturePictureSnapshot -> capture()
            R.id.ivCameraSwitch -> toggleCamera()
            R.id.ivLight -> setLight()
//            R.id.changeFilter -> changeCurrentFilter()
            R.id.mark -> chooseMark()
            R.id.timing -> changeTime()
            R.id.gallery -> choosePic()
            R.id.tv_puzzle -> showSize()
            R.id.ic_camera_ratio_3_4 -> changeSize(0)
            R.id.ic_camera_ratio_9_16 -> changeSize(1)
            R.id.ic_camera_ratio_1_1 -> changeSize(2)
            R.id.ic_camera_ratio_full -> changeSize(3)
        }
    }

    var size = 0
    private fun showSize() {
        if (binding.size.root.visibility != View.VISIBLE) {
            binding.size.root.visibility = View.VISIBLE
        } else {
            binding.size.root.visibility = View.GONE
        }
    }

    private fun changeSize(i: Int) {
        if (i == size) {
            return
        }
        if (size == 3) {
            (binding.frame.layoutParams as RelativeLayout.LayoutParams).addRule(
                RelativeLayout.BELOW, R.id.top
            )
            binding.backIv.setImageResource(R.drawable.back_home)
            binding.ivCameraSwitch.setImageResource(R.drawable.icon_camera_switch)
            when (time) {
                0 -> binding.timing.setImageResource(R.drawable.timing_icon)
                1 -> binding.timing.setImageResource(R.drawable.icon_camera_timing_5)
                2 -> binding.timing.setImageResource(R.drawable.icon_camera_timing_10)
            }
            binding.tvPuzzle.setImageResource(R.drawable.puzzle_icon)
            if (camera.flash == Flash.TORCH) {
                binding.ivLight.setImageResource(R.drawable.icon_camera_light_open)
            } else {
                binding.ivLight.setImageResource(R.drawable.icon_camera_light_close)
            }
            binding.ivClose.setImageResource(R.drawable.icon_camera_more)
        }
        size = i
        for (tab in sizeTabs) {
            tab.setSelect(false)
        }
        sizeTabs[i].setSelect(true)
        when (i) {
            0 -> {
                binding.frame.ratio = 1.33
                binding.ivAlbum.setBackgroundResource(R.drawable.icon_camera_album)
                binding.ivWater.setImageResource(R.drawable.icon_camera_watermark)
                binding.ivTake.setImageResource(R.drawable.bg_camera_take_blue)
                binding.tvAlbum.setTextColor(Color.DKGRAY)
                binding.tvWater.setTextColor(Color.DKGRAY)
                binding.bottom.background = null
            }

            1 -> {
                binding.frame.ratio = 1.78
                binding.ivAlbum.setBackgroundResource(R.drawable.icon_camera_album_white)
                binding.ivWater.setImageResource(R.drawable.icon_camera_watermark_white)
                binding.ivTake.setImageResource(R.drawable.bg_camera_take_white)
                binding.tvAlbum.setTextColor(Color.WHITE)
                binding.tvWater.setTextColor(Color.WHITE)
                binding.bottom.setBackgroundColor(0x33000000)
            }

            2 -> {
                binding.frame.ratio = 1.0
                binding.ivAlbum.setBackgroundResource(R.drawable.icon_camera_album)
                binding.ivWater.setImageResource(R.drawable.icon_camera_watermark)
                binding.tvAlbum.setTextColor(Color.DKGRAY)
                binding.tvWater.setTextColor(Color.DKGRAY)
                binding.bottom.background = null
            }

            3 -> {
                binding.frame.ratio = 0.0
                (binding.frame.layoutParams as RelativeLayout.LayoutParams).removeRule(
                    RelativeLayout.BELOW
                )
                binding.ivAlbum.setBackgroundResource(R.drawable.icon_camera_album_white)
                binding.ivWater.setImageResource(R.drawable.icon_camera_watermark_white)
                binding.tvAlbum.setTextColor(Color.WHITE)
                binding.tvWater.setTextColor(Color.WHITE)
                binding.bottom.setBackgroundColor(0x33000000)
                binding.backIv.setImageResource(R.drawable.back_white)
                binding.ivCameraSwitch.setImageResource(R.drawable.icon_camera_switch_white)
                when (time) {
                    0 -> binding.timing.setImageResource(R.drawable.timing_icon_white)
                    1 -> binding.timing.setImageResource(R.drawable.timing_icon_white_5)
                    2 -> binding.timing.setImageResource(R.drawable.timing_icon_white_10)
                }
                binding.tvPuzzle.setImageResource(R.drawable.puzzle_icon_white)
                if (camera.flash == Flash.TORCH) {
                    binding.ivLight.setImageResource(R.drawable.icon_camera_light_open_white)
                } else {
                    binding.ivLight.setImageResource(R.drawable.icon_camera_light_close_white)
                }
                binding.ivClose.setImageResource(R.drawable.icon_camera_more_white)
            }
        }
        binding.frame.requestLayout()
    }

    private var time = 0;
    private fun changeTime() {
        if (++time > 2) {
            time = 0
        }
        when (time) {
            0 -> binding.timing.setImageResource(R.drawable.timing_icon)
            1 -> binding.timing.setImageResource(R.drawable.icon_camera_timing_5)
            2 -> binding.timing.setImageResource(R.drawable.icon_camera_timing_10)
        }
    }

    private fun setLight() {
        if (camera.flash == Flash.TORCH) {
            camera.flash = Flash.OFF
            binding.ivLight.setImageResource(R.drawable.icon_camera_light_close)
        } else {
            camera.flash = Flash.TORCH
            binding.ivLight.setImageResource(R.drawable.icon_camera_light_open)
        }
    }

    private fun choosePic() {
        Read.toRead(this, Runnable {
            val i = Intent(this, PreviewPhotoAct::class.java)
            i.putExtra("mode", if (camera.mode == Mode.VIDEO) 1 else 0)
            startActivity(i)
        })
    }

    private var markDlg: MarkDlg? = null

    private fun chooseMark() {
        if (camera.mode == Mode.VIDEO) {
            if ("保存" == binding.tvWater.text.toString()) {
                if (camera.isTakingVideo) {
                    saveVideo = true
                    camera.stopVideo()
                    h.removeCallbacks(updateRecordTime)
                    binding.time.visibility = View.INVISIBLE
                    binding.ivTakeCenter.setImageResource(R.drawable.bg_camera_take_video_normal)
                } else {
                    saveVideo()
                }
                return
            }
        }
        markDlg = MarkDlg()
        markDlg!!.setOnDismissListener { _, _ -> markDlg = null }
        markDlg!!.show(supportFragmentManager, "mark")
    }

    private fun saveVideo() {
        var f = File(filesDir, videoName)
        Read.toRead(this, Runnable {
            TaskEngine.getInstance().submit(object : SilentTask("") {
                @Throws(Exception::class)
                override fun runInBackground() {
                    var bm = getFirstFrame(f)
                    h.post {
                        binding.ivAlbum.setImageBitmap(bm)
                        SaveUtils.saveVideoToAlbum(App.getApp(), f.absolutePath)
                        ToastUtil.showShortToast(App.getApp(), "保存到相册")
                        binding.ivWater.setImageResource(R.drawable.icon_camera_watermark_white)
                        binding.tvWater.text = "水印"
                        startVideo = false
                    }
                }
            })
        })
    }

    private fun getFirstFrame(file: File): Bitmap? {
        try {
            // 创建MediaMetadataRetriever对象
            // 创建MediaMetadataRetriever对象
            val retriever = MediaMetadataRetriever()
            // 设置数据源
            // 设置数据源
            retriever.setDataSource(file.absolutePath)
// 获取第一帧图像
// 获取第一帧图像
            return retriever.frameAtTime
        } catch (e: Throwable) {
            e.printStackTrace()
        }
        return null
    }

    var countDown = false

    private fun capture() {
        if (countDown) {
            return
        }
        if (camera.mode == Mode.VIDEO && camera.isTakingVideo) {
            doCapture()
            return
        }
        if (time == 0) {
            doCapture();
        } else if (time == 1) {
            countDown = true
            binding.countDown.visibility = View.VISIBLE
            binding.countDown.text = "5"
            val countDownTimer: CountDownTimer = object : CountDownTimer(6000, 1000) {
                override fun onTick(millisUntilFinished: Long) {
                    // 更新倒计时显示
                    binding.countDown.text = (millisUntilFinished / 1000).toString()
                }

                override fun onFinish() {
                    // 倒计时结束后的操作
                    countDown = false
                    binding.countDown.visibility = View.GONE
                    doCapture()
                }
            }
            countDownTimer.start()
        } else if (time == 2) {
            countDown = true
            binding.countDown.visibility = View.VISIBLE
            binding.countDown.text = "10"
            val countDownTimer: CountDownTimer = object : CountDownTimer(11000, 1000) {
                override fun onTick(millisUntilFinished: Long) {
                    // 更新倒计时显示
                    binding.countDown.text = (millisUntilFinished / 1000).toString()
                }

                override fun onFinish() {
                    // 倒计时结束后的操作
                    countDown = false
                    binding.countDown.visibility = View.GONE
                    doCapture()
                }
            }
            countDownTimer.start()
        }
    }

    private fun doCapture() {
        if (camera.mode == Mode.PICTURE) {
            capturePictureSnapshot()
        } else {
            captureVideoSnapshot()
        }
    }

    private fun capturePictureSnapshot() {
        if (camera.isTakingPicture) return
        if (camera.preview != Preview.GL_SURFACE) return run {
            message("Picture snapshots are only allowed with the GL_SURFACE preview.", true)
        }
        captureTime = System.currentTimeMillis()
        message("Capturing picture snapshot...", false)
        camera.takePictureSnapshot()
    }

    private fun toggleCamera() {
        if (camera.isTakingPicture || camera.isTakingVideo) return
        when (camera.toggleFacing()) {
            Facing.BACK -> message("Switched to back camera!", false)
            Facing.FRONT -> message("Switched to front camera!", false)
        }
    }

    override fun <T : Any> onValueChanged(option: Option<T>, value: T, name: String): Boolean {
        if (option is Option.Width || option is Option.Height) {
            val preview = camera.preview
            val wrapContent = value as Int == WRAP_CONTENT
            if (preview == Preview.SURFACE && !wrapContent) {
                message(
                    "The SurfaceView preview does not support width or height changes. " +
                            "The view will act as WRAP_CONTENT by default.", true
                )
                return false
            }
        }
        option.set(camera, value)
        message("Changed " + option.name + " to " + name, false)
        return true
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        val valid = grantResults.all { it == PERMISSION_GRANTED }
        if (valid && !camera.isOpened) {
            camera.open()
        }
    }

    private var startVideo = false
    private var saveVideo = false
    private var videoName = ""
    private var recordTime = 0L
    private val updateRecordTime = object : Runnable {
        override fun run() {
            recordTime += 1;
            var m = recordTime / 60
            var s = recordTime % 60
            var hour = 0L
            if (m >= 60) {
                hour = m / 60
                m %= 60
            }
            var str = ""
            if (hour > 0) {
                str = String.format("%02d", hour) + ":" + String.format(
                    "%02d",
                    m
                ) + ":" + String.format("%02d", s)
            } else {
                str = String.format("%02d", m) + ":" + String.format("%02d", s)
            }
            binding.time.text = str
            h.postDelayed(this, 1000)
        }
    }

    private fun captureVideoSnapshot() {
        if (camera.isTakingVideo) return run {
            camera.stopVideo()
            h.removeCallbacks(updateRecordTime)
            binding.time.visibility = View.INVISIBLE
            binding.ivTakeCenter.setImageResource(R.drawable.bg_camera_take_video_normal)
//            message("Already taking video.", false)
        }
        if (camera.preview != Preview.GL_SURFACE) return run {
            message("Video snapshots are only allowed with the GL_SURFACE preview.", true)
        }
        if (!TextUtils.isEmpty(videoName)) {
            File(filesDir, videoName).delete()
        }
        binding.ivTakeCenter.setImageResource(R.drawable.bg_camera_take_video_pause)
        videoName = "video" + System.currentTimeMillis() + ".mp4"
        camera.takeVideoSnapshot(File(filesDir, videoName))
        binding.ivWater.setImageResource(R.drawable.icon_camra_save_video)
        binding.tvWater.text = "保存"
        startVideo = true
        saveVideo = false
        binding.time.visibility = View.VISIBLE
        recordTime = 0
        h.post(updateRecordTime)
    }

    override fun onDestroy() {
        super.onDestroy()
        if (!TextUtils.isEmpty(videoName)) {
            File(filesDir, videoName).delete()
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 102) {//editMarkActivity
            if (resultCode == Activity.RESULT_OK) {
                waterMark?.update()
            }
        }
    }
}
